package com.example.archivemanagement.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.archivemanagement.audit.AuditEvent;
import com.example.archivemanagement.audit.AuditEventProducer;
import com.example.archivemanagement.common.CommonConstant;
import com.example.archivemanagement.entity.Archive;
import com.example.archivemanagement.entity.User;
import com.example.archivemanagement.security.UserPrincipal;
import com.example.archivemanagement.service.ArchiveService;
import com.example.archivemanagement.service.StatisticsService;
import com.example.archivemanagement.utils.SparkUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/archives")
@CrossOrigin(origins = "*", maxAge = 3600)
public class ArchiveController {

    @Autowired
    private ArchiveService archiveService;

    @Autowired
    private StatisticsService statisticsService;

    @Autowired
    private AuditEventProducer auditEventProducer;

    @PostMapping("/upload")
    @PreAuthorize("isAuthenticated()")
    public ResponseEntity<?> uploadArchive(
            @RequestParam("file") MultipartFile file,
            @RequestParam("name") String name,
            @RequestParam("category") String category,
            @RequestParam("securityLevel") String securityLevel,
            @RequestParam(value = "description", required = false) String description) {

        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Archive archive = new Archive();
        if (principal instanceof UserPrincipal) {
            UserPrincipal userPrincipal = (UserPrincipal) principal;
            archive.setUploadUserId(userPrincipal.getId());
        }
        String newName = name.trim().replace(",", "");
        archive.setName(newName);
        archive.setCategory(category);
        archive.setSecurityLevel(securityLevel);
        archive.setDescription(description);
        String archiveNumber = CommonConstant.generateRandomName();
        archive.setArchiveNumber(archiveNumber);
        archive.setCreateTime(LocalDateTime.now());
        
        Archive savedArchive = archiveService.uploadArchive(file, archive);
        statisticsService.addDownloadCount(name);
        AuditEvent event = new AuditEvent("upload",
                archiveNumber, "上传",
                SparkUtils.getCurrentUsername(), LocalDateTime.now(), "");

        auditEventProducer.sendAuditEvent(event);
        return ResponseEntity.ok(savedArchive);
    }

    @GetMapping("/recent")
    public ResponseEntity<?> getRecentArchives(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        boolean isAdmin = false;
        if (principal instanceof UserPrincipal) {
            UserPrincipal userPrincipal = (UserPrincipal) principal;
            String realName = userPrincipal.getRealName();
            if ("系统管理员".equals(realName)) {
                isAdmin = true;
            }
        }
        Page<Archive> archives = archiveService.getRecentArchives(isAdmin, page, size);
        return ResponseEntity.ok(archives);
    }

    @GetMapping("/search")
    public ResponseEntity<?> searchArchives(
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String category,
            @RequestParam(required = false) String securityLevel,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        boolean isAdmin = false;
        if (principal instanceof UserPrincipal) {
            UserPrincipal userPrincipal = (UserPrincipal) principal;
            String realName = userPrincipal.getRealName();
            if ("系统管理员".equals(realName)) {
                isAdmin = true;
            }
        }
        Page<Archive> archives = archiveService.searchArchives(isAdmin, keyword, category, securityLevel, page, size);
        return ResponseEntity.ok(archives);
    }

    @GetMapping("/{id}")
    public ResponseEntity<?> getArchive(@PathVariable Long id) {
        Archive archive = archiveService.getById(id);
        if (archive == null) {
            return ResponseEntity.notFound().build();
        }
        statisticsService.addMonthViews();
        return ResponseEntity.ok(archive);
    }

    @GetMapping("/vew/{id}")
    public ResponseEntity<?> view(@PathVariable Long id) {
        String content = archiveService.view(id);
        statisticsService.addMonthViews();
        return ResponseEntity.ok(content);
    }

    @PutMapping("/{id}")
    @PreAuthorize("isAuthenticated()")
    public ResponseEntity<?> updateArchive(@PathVariable Long id, @RequestBody Archive archive) {
        archive.setId(id);
        archive.setUpdateTime(LocalDateTime.now());
        Archive updatedArchive = archiveService.updateArchive(archive);
        statisticsService.addMonthViews();
        return ResponseEntity.ok(updatedArchive);
    }

    @DeleteMapping("/{id}")
    @PreAuthorize("isAuthenticated()")
    public ResponseEntity<?> deleteArchive(@PathVariable Long id) {
        archiveService.deleteArchive(id);
        return ResponseEntity.ok().build();
    }

    /**
     * 根据类别查找
     * @param category
     * @return
     */
    @GetMapping("/category/{category}")
    public ResponseEntity<?> getArchivesByCategory(@PathVariable String category) {
        List<Archive> archives = archiveService.getArchivesByCategory(category);
        return ResponseEntity.ok(archives);
    }

    /**
     * 根据安全类型查找
     * @param level
     * @return
     */
    @GetMapping("/security-level/{level}")
    public ResponseEntity<?> getArchivesBySecurityLevel(@PathVariable String level) {
        List<Archive> archives = archiveService.getArchivesBySecurityLevel(level);
        return ResponseEntity.ok(archives);
    }

    /**
     * 馆藏统计
     * @return
     */
    @GetMapping("/security-level")
    public ResponseEntity<?> getArchives() {
        Map<String, Long> archives = archiveService.getArchives();
        return ResponseEntity.ok(archives);
    }
} 